<template>
  <view>
    <view class="inline-flex m-1 space-x-1" v-for="(item,index) in categoryList" :key="index">
      <u-tag @click="handleClick(item)" class="cursor-pointer" :text="item" :plain="item!==curValue"
             :closable="item===curValue" @close="handleRemove(item)"></u-tag>
    </view>
    <view class="inline-flex m-1 space-x-1">
      <u-tag v-if="isEdit" plain>
        <template #icon>
          <input :focus="true" type="text" class="w-max text-center" v-model="newCategory"
                 @confirm="handleFinish" @blur="handleFinish">
        </template>
      </u-tag>
      <u-tag v-else plain @click="handleNew">
        <template #icon>
          <u-icon class="cursor-pointer" name="plus" color="#59ABFF"></u-icon>
        </template>
      </u-tag>
    </view>
  </view>
</template>
<script setup lang="ts">

import {useProductStore} from "@/store/product";
import {storeToRefs} from "pinia";
import {computed, ref} from "vue";

const props = defineProps({
  value: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['update:value'])
const curValue = computed({
  get() {
    return props.value
  },
  set(val) {
    emits('update:value', val)
  }
})

const productStore = useProductStore()
const {categoryList} = storeToRefs(productStore)
const newCategory = ref('')
const isEdit = ref(false)

const handleClick = (item: string) => {
  curValue.value = item
}
const handleNew = () => {
  isEdit.value = true
}
const handleFinish = () => {
  if (newCategory.value) {
    categoryList.value.push(newCategory.value)
    curValue.value = newCategory.value
    newCategory.value = ''
  }
  isEdit.value = false
}
const handleRemove = (item: string) => {
  categoryList.value = categoryList.value.filter(i => i !== item)
}
</script>

<style scoped>
</style>